<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/11/25 0025
 * Time: 9:19
 */
namespace app\adminapi\controller;

use app\adminapi\model\Api;
use app\api\model\JWT;
use think\App;
use think\Controller;
use think\Db;
use think\Request;
require_once '../vendor/phpexcel/PHPExcel/IOFactory.php';
/**
 * @title 初期信息导入
 * @description 接口说明
 */
class Import extends Api
{
    /**
     * @title 初期信息导入（不用）
     * @description 接口说明
     * @author 开发者
     * @url /adminapi/Import/index
     * @method POST
     * @param name:file type:int require:1 default: other: desc:表格
     * 
     */
    public function index()
    {
        $user = $this->user;
        $scheduled = db::name('scheduled')->where('hid',$user['hid'])->where('is_del',2)->select();
        if($scheduled){
            // return $this->ajaxReturn(1,'已产生订单，不可导入');
        }
        $file= $this->request->file("file");
        if ($file){
            $info = $file->move($_SERVER['DOCUMENT_ROOT'].'/uploads/files');
            if ($info){
                // 成功上传后 获取上传信息
                $url=$info->getSaveName();
                $file_info = [
                    'uid'    => $user['id'],
                    'name'   => $file->getInfo('name'),
                    'mime'   => $file->getInfo('type'),
                    'path'   => 'uploads/files/'.$url,
                    'ext'    => $info->getExtension(),
                    'size'   => $info->getSize(),
                    'md5'    => $info->hash('md5'),
                    'sha1'   => $info->hash('sha1'),
                    'thumb'  => '',
                    'module' => '',
                    'width'  => '',
                    'height' => '',
                ];
                $excel_file = db::name('admin_attachment')->insertGetId($file_info);
            }else{
                // 上传失败获取错误信息
                return $this->ajaxReturn(1,'上传失败');
            }
        }
        // 获取附件 ID 完整路径
        $full_path =  getcwd() . '/'.$file_info['path'];
        // print_R($full_path);die;
        $file_infos = explode('.', $full_path);
        $file_ext  = strtolower(end($file_infos));
        if ($file_ext != 'xls' && $file_ext != 'xlsx') {
            return $this->ajaxReturn(1,'文件格式错误');
        }

        $fileName = '宴会厅订单.xls';
        $fileNames = '宴会厅订单.xlsx';

        $confirmName = '确认方式.xls';
        $confirmNames = '确认方式.xlsx';


        if(strpos($file_info['name'],$fileName) !== false ||strpos($file_info['name'],$fileNames) !== false){
            // 宴会厅
            $banquet = db::name('banquet')->where('hid',$user['hid'])->where('is_del',1)->count();
            // 宴会厅类型
            $banquet_type = db::name('banquet_types')->where('hid',$user['hid'])->where('is_del',1)->count();
            // 客户经理
            $users = db::name('user')->where('hid',$user['hid'])->count();
            // 餐标
            $ds = db::name('ds')->where('hid',$user['hid'])->where('is_del',1)->count();
            // 客户来源
            $source = db::name('source')->where('hid',$user['hid'])->where('type',1)->where('is_del',1)->count();
            // 增值服务
            $increase = db::name('increase')->where('hid',$user['hid'])->where('is_del',1)->count();

            if($banquet && $banquet_type && $users && $ds && $source && $increase){
                // 只导入的字段列表
                $fields = [
                    'book' => '姓名',
                    'sex' => '性别',
                    'mobile' => '电话',
                    'addtime' => '预定时间（年/月/日）',
                    'b_name' => '宴会厅',
                    't_name' => '宴会类型',
                    'begin' => '使用时间（年/月/日）',
                    'begin_night' => '使用时段',
                    'end' => '结束时间（仅会议填写）',
                    'end_night' => '结束时段（仅会议填写）',
                    'desk' => '桌数',
                    'prepare_desk' => '备桌（宴会使用）',
                    'd_name' => '餐标',
                    'source' => '客户来源',
                    'director' => '客户经理',
                    'content' => '备注',
                    'increase_money' => '增值金额',
                ];
                $database = 'scheduled';
                $types = 1;
            }else{
                return $this->ajaxReturn(1,'必填信息填写不完整');
            }
            
        }else{
            return $this->ajaxReturn(1,'请上传正确的文件');
        }
        
        // 调用插件('插件',[路径,导入表名,字段限制,类型,条件,重复数据检测字段])
        $import = plugin_action('Excel/Excel/import', [$full_path, $database, $fields, $type = 0, $where = null, $main_field = 'begin',$user = $user,$types=$types]);
        if($import['error'] == 0){
            return $this->ajaxReturn(0,$import['message']);
        }else{
            return $this->ajaxReturn(1,$import['message']);
        }
    }


    /**
     * @title 确认方式导入（不用）
     * @description 接口说明
     * @author 开发者
     * @url /adminapi/Import/confirm
     * @method POST
     * @param name:file type:int require:1 default: other: desc:表格
     * 
     */
    public function confirm()
    {
        $user = $this->user;
        $scheduled = db::name('scheduled')->where('hid',$user['hid'])->where('is_del',2)->select();
        if(!$scheduled){
            return $this->ajaxReturn(1,'请先添加订单');
        }
        $file= $this->request->file("file");
        if ($file){
            $info = $file->move($_SERVER['DOCUMENT_ROOT'].'/uploads/files');
            if ($info){
                // 成功上传后 获取上传信息
                $url=$info->getSaveName();
                $file_info = [
                    'uid'    => $user['id'],
                    'name'   => $file->getInfo('name'),
                    'mime'   => $file->getInfo('type'),
                    'path'   => 'uploads/files/'.$url,
                    'ext'    => $info->getExtension(),
                    'size'   => $info->getSize(),
                    'md5'    => $info->hash('md5'),
                    'sha1'   => $info->hash('sha1'),
                    'thumb'  => '',
                    'module' => '',
                    'width'  => '',
                    'height' => '',
                ];
                $excel_file = db::name('admin_attachment')->insertGetId($file_info);
            }else{
                // 上传失败获取错误信息
                return $this->ajaxReturn(1,'上传失败');
            }
        }
        // 获取附件 ID 完整路径
        $full_path =  getcwd() . '/'.$file_info['path'];
        // print_R($full_path);die;
        $file_infos = explode('.', $full_path);
        $file_ext  = strtolower(end($file_infos));
        if ($file_ext != 'xls' && $file_ext != 'xlsx') {
            return $this->ajaxReturn(1,'文件格式错误');
        }

        $confirmName = '确认方式.xls';
        $confirmNames = '确认方式.xlsx';

        // https://lxy.yskxfs.com/apple-app-site-association
        if(strpos($file_info['name'],$confirmName) !== false ||strpos($file_info['name'],$confirmNames) !== false){

            // 只导入的字段列表
            $fields = [
                'name' => '姓名',
                'age' => '年龄',
            ];
            $types = 2;
            $database = 'scheduled';

        }else{
            return $this->ajaxReturn(1,'请上传正确的文件');
        }
        
        // 调用插件('插件',[路径,导入表名,字段限制,类型,条件,重复数据检测字段])
        $import = plugin_action('Excel/Excel/import', [$full_path, $database, $fields, $type = 0, $where = null, $main_field = 'begin',$user = $user,$types=$types]);
        if($import['error'] == 0){
            return $this->ajaxReturn(0,$import['message']);
        }else{
            return $this->ajaxReturn(1,$import['message']);
        }
    }

     /**
     * @title 初期信息导入
     * @description 接口说明
     * @author 开发者
     * @url /adminapi/Import/uplExcel
     * @method POST
     * @param name:excel type:int require:1 default: other: desc:表格
     * 
     */
    public function uplExcel(Request $request)
    {
        $user = $this->user;
        if (!empty($_FILES['excel']['name'])) {
            $fileName = $_FILES['excel']['name'];    //得到文件全名
            $dotArray = explode('.', $fileName);    //把文件名安.区分，拆分成数组
            $type = end($dotArray);
            if ($type != "xls" && $type != "xlsx") {
                return $this->ajaxReturn(1,'不是Excel文件，请重新上传!');

            }
    
            //取数组最后一个元素，得到文件类型
            $uploaddir = "../public/uploads/files/" . date("Y-m-d") . '/';//设置文件保存目录 注意包含
            if (!file_exists($uploaddir)) {
                mkdir($uploaddir, 0777, true);
            }
    
            $path = $uploaddir . md5(uniqid(rand())) . '.' . $type; //产生随机文件名
            //$path = "images/".$fileName; //客户端上传的文件名；
            //下面必须是tmp_name 因为是从临时文件夹中移动
            move_uploaded_file($_FILES['excel']['tmp_name'], $path); //从服务器临时文件拷贝到相应的文件夹下
    
            $file_path = $path;
            if (!file_exists($path)) {
                return $this->ajaxReturn(1,'上传文件丢失');

            }
            //文件的扩展名
            $ext = strtolower(pathinfo($path, PATHINFO_EXTENSION));
            if ($ext == 'xlsx') {
                $objReader = \PHPExcel_IOFactory::createReader('Excel2007');
                $objPHPExcel = $objReader->load($file_path, 'utf-8');
            } elseif ($ext == 'xls') {
                $objReader = \PHPExcel_IOFactory::createReader('Excel5');
                $objPHPExcel = $objReader->load($file_path, 'utf-8');
            }
            $sheet = $objPHPExcel->getSheet(0);
            $highestRow = $sheet->getHighestRow(); // 取得总行数
            $highestColumn = $sheet->getHighestColumn(); // 取得总列数
     
            if($highestColumn == 'Q'){
                $scheduled = db::name('scheduled')->where('hid',$user['hid'])->where('is_del',2)->select();
                // if($scheduled){
                //     return $this->ajaxReturn(1,'已产生订单,不可再导入');
                // }

                // 宴会厅
                $banquet = db::name('banquet')->where('hid',$user['hid'])->where('is_del',1)->count();
                // 宴会厅类型
                $banquet_type = db::name('banquet_types')->where('hid',$user['hid'])->where('is_del',1)->count();
                // 客户经理
                $users = db::name('user')->where('hid',$user['hid'])->count();
                // 餐标
                $ds = db::name('ds')->where('hid',$user['hid'])->where('is_del',1)->count();
                // 客户来源
                $source = db::name('source')->where('hid',$user['hid'])->where('type',1)->where('is_del',1)->count();
                // 增值服务
                $increase = db::name('increase')->where('hid',$user['hid'])->where('is_del',1)->count();
                if($banquet && $banquet_type && $users && $ds && $source && $increase){
                    
                }else{
                    return $this->ajaxReturn(1,'必要信息填写不完整');
                }

            }elseif($highestColumn == 'J'){
                $scheduled = db::name('scheduled')->where('hid',$user['hid'])->where('is_del',2)->select();
                if(!$scheduled){
                    return $this->ajaxReturn(1,'请先添加订单');
                }
                $deposit = db::name('scheduled_deposit')->where('hid',$user['hid'])->select();
                // if($deposit){
                //     return $this->ajaxReturn(1,'已产生订单,不可再导入');
                // }
                // 支付方式
                $pay = db::name('deposit')->where('hid',$user['hid'])->where('type',2)->where('is_del',1)->select();
                $deposits = db::name('deposit')->where('hid',$user['hid'])->where('type',1)->where('is_del',1)->select();
                // print_R($pay);
                // print_r($deposits);die;
                if(!$pay || !$deposits){
                    return $this->ajaxReturn(1,'必要信息填写不完整');
                }
            }else{
                return $this->ajaxReturn(1,'表格信息错误');
            }



            $i = 0;
            $array = [];

            $PHPReader = $objReader->load($file_path);

            $allWorksheets = $PHPReader->getAllSheets(); //获取所有工作表

            //循环读取每个工作表
            foreach($allWorksheets as $objWorksheet){
                $sheet_name = $objWorksheet->getTitle(); //获取当前工作表名
                $allRow = $objWorksheet->getHighestRow();//当前工作表的行数
                $highestColumn = $objWorksheet->getHighestColumn();//当前工作表的列数，excel以字母表示列数，比如B表示2列
                $allColumn = \PHPExcel_Cell::columnIndexFromString($highestColumn); //当前工作表的列数，将字母表示的列数转换为数字
                $array[$i]["Title"] = $sheet_name;
                $array[$i]["Cols"]  = $allColumn;
                $array[$i]["Rows"]  = $allRow;
                $arr = [];
                $isMergeCell = [];
                foreach ($objWorksheet->getMergeCells() as $cells) {//找出合并单元格
                    foreach (\PHPExcel_Cell::extractAllCellReferencesInRange($cells) as $cellReference) {
                        $isMergeCell[$cellReference] = true;
                    }
                }

                for($currentRow = 1; $currentRow <= $allRow; $currentRow++){
                    $row = [];
                    for($currentColumn = 0; $currentColumn < $allColumn; $currentColumn++){
                        $cell    = $objWorksheet->getCellByColumnAndRow($currentColumn, $currentRow);
                        $afCol   = \PHPExcel_Cell::stringFromColumnIndex($currentColumn+1); //后一列的索引，比如当前列为A，后一列则为B
                        $bfCol   = \PHPExcel_Cell::stringFromColumnIndex($currentColumn-1); //前一列的索引，如果当前列为第一列，则前一列索引为@
                        $col     = \PHPExcel_Cell::stringFromColumnIndex($currentColumn); //当前列的索引
                        $address = $col.$currentRow;//当前单元格的位置
                        $value   = $objWorksheet->getCell($address)->getValue(); //当前单元格的值
                        $value   = trim($value); //去除首尾空格
                        // 如果当前行的第一个单元格内容为空，则跳过当前行
                        if ($currentColumn == 0 && ($value == '' || $value === NULL)) {
                            break;
                        }
                        if(substr($value,0,1) == '='){//判断单元格的公式不完整的情况
                            return $this->ajaxReturn(1,'无法使用公式!');
                            // return ["error" => 7, 'message' => '无法使用公式!']; //can not use the formula!
                        }

                        //判断单元格是否为数字类型
                        if($cell->getDataType() == \PHPExcel_Cell_DataType::TYPE_NUMERIC){
                            // $cell_style_format=$cell->getParent()->getStyle( $cell->getCoordinate() )->getNumberFormat();
                            $cell_style_format = $cell->getStyle($cell->getCoordinate())->getNumberFormat(); //不需要getParent
                            $format_code = $cell_style_format->getFormatCode();
                            if (preg_match('/^([$[A-Z]*-[0-9A-F]*])*[hmsdy]/i', $format_code)) { //判断是否为日期类型
                                $value = gmdate("Y-m-d", \PHPExcel_Shared_Date::ExcelToPHP($value)); //格式化日期
                            }else{
                                $value = \PHPExcel_Style_NumberFormat::toFormattedString($value, $format_code); //格式化数字
                            }
                        }
                        //处理该单元格为合并单元格的情况
                        $temp = '';
                        if(isset($isMergeCell[$col.$currentRow]) && isset($isMergeCell[$afCol.$currentRow]) && !empty($value)){
                            $temp = $value;
                        }elseif(isset($isMergeCell[$col.$currentRow]) && isset($isMergeCell[$col.($currentRow-1)]) && empty($value)){
                            $value = $arr[$currentRow-1][$currentColumn];
                        }elseif(isset($isMergeCell[$col.$currentRow]) && isset($isMergeCell[$bfCol.$currentRow]) && empty($value)){
                            $value = $temp;
                        }
                        $row[$currentColumn] = $value;
                    }
                    //判断一行中的全部单元格是否都有数据
                    //如果不是，给出提示
                    if (count($row) != 0 && count($row) != $allColumn) {
                        // $mes = "工作表【{$sheet_name}】的第【{$currentRow}】行的数据不完整，请填写完整，并重新导入";
                        // return $this->ajaxReturn(1, $mes);
                        // return ["error" => 4, 'message' => "工作表【{$sheet_name}】的第【{$currentRow}】行的数据不完整，请填写完整，并重新导入");
                    }

                    $arr[$currentRow] = $row; //完整一行的数据
                }
                $array[$i]["Content"] = array_filter($arr);//过滤空行
                $i++;
            }
            unset($objWorksheet);
            unset($PHPReader);
            unset($PHPExcel);
            // print_r($highestColumn);die;
            if($highestColumn == 'Q'){
                $where[] = ['hid','=',$user['hid']];
                $where[] = ['type','=',2];
                $main_field = ['bid','tid','begin_year','begin_month','begin_day','begin_night'];
                $exists_list = Db::name('scheduled')->where($where)->field($main_field)->select();
                if($exists_list){
                    $newArr = [];
                    $newArrs = [];
                    foreach ($exists_list as $k=>$v) {
                        $exists_list[$k]['begin'] = $v['begin_year'] . '-' .$v['begin_month'] . '-' .$v['begin_day'];
                        $newArr[] = $exists_list[$k]['begin'];
                        $newArrs[] = $exists_list[$k]['begin_night'];
                    }
                }else{
                    $newArr = [];
                    $newArrs = [];
                }
                $fields = [
                    'book' => '姓名',
                    'sex' => '性别',
                    'mobile' => '电话',
                    'addtime' => '预定时间（年/月/日）',
                    'b_name' => '宴会厅',
                    't_name' => '宴会类型',
                    'begin' => '使用时间（年/月/日）',
                    'begin_night' => '使用时段',
                    'end' => '结束时间（仅会议填写）',
                    'end_night' => '结束时段（仅会议填写）',
                    'desk' => '桌数',
                    'prepare_desk' => '备桌（宴会使用）',
                    'd_name' => '餐标',
                    'source' => '客户来源',
                    'director' => '客户经理',
                    'content' => '备注',
                    'increase_money' => '增值金额',
                ];
            }elseif($highestColumn == 'J'){
                $where[] = ['hid','=',$user['hid']];
                $main_field = ['num','id','money'];
                $exists_list = Db::name('scheduled_deposit')->where($where)->field($main_field)->select();
                if($exists_list){
                    $newArr = [];
                    $newArrs = [];
                    foreach ($exists_list as $k=>$v) {
                        $newArr[] = $exists_list[$k]['num'];
                    }
                }else{
                    $newArr = [];
                    $newArrs = [];
                }
                $fields = [
                    'num' => '收据编号',
                    'type_name' => '押金名称',
                    'pay_name' => '支付名称',
                    'addtime' => '支付时间（年/月/日）',
                    'money' => '押金金额',

                    'manager' => '客户经理',
                    'order' => '订单时间（年/月/日）',
                    'begin_night' => '订单使用时段',
                    
                    'end' => '会议时间（年/月/日）',
                    'end_night' => '会议使用时段',
                    
                ];
            }
            $fields    = array_flip($fields); //反转键值
            $data_list = [];
            $dataAdd['list']   = [];
            $dataCover['list'] = [];
            $dataSkip['list']  = [];
            foreach ($array as $key => $value) { //循环每一张工作表
                $firstRow = [];
                foreach ($value['Content'] as $row => $col) { //循环每一行数据
                    $data = [];
                    if ($row == 1) { //处理excel表的第一行，即表头，用来获取表头与字段名的关系
                        foreach ($col as $index => $val) { //循环每一个单元格
                            if (isset($fields[$val])) {
                                $firstRow[$index] = $fields[$val];
                            }
                        }
                    } else { //这里开始是真正需要的数据
                        if (empty($firstRow)) {
                            return $this->ajaxReturn(1,'没有表头数据，无法导入!');
                            // return ["error" => 8, 'message' => '没有表头数据，无法导入!'];
                        }
                        foreach ($col as $index => $val) { //循环每一个单元格
                            if (isset($firstRow[$index])) {
                                $data[$firstRow[$index]] = trim($val);
                            }
                        }
                        if($highestColumn == 'Q'){
                            if (in_array($data['begin'], $newArr)) {
                                $keys = array_search($data['begin'], $newArr);
                                if($keys){
                                    if($data['begin_night']){
                                        if(strpos($data['begin_night'],'中午') !== false){        
                                            $begin_night = 1;
                                        }
                                        if(strpos($data['begin_night'],'下午') !== false){        
                                            $begin_night = 2;
                                        }
                                        if(strpos($data['begin_night'],'晚上') !== false){        
                                            $begin_night = 2;
                                        }
                                    }
                                    if($begin_night == $newArrs[$keys]){
                                        $dataSkip['list'][] = $data['begin']; //记录跳过的数据
                                        continue;//跳过已存在的考生
                                    }
                                }
                            } else {
                                $dataAdd['list'][] = $data['begin']; //记录新增的数据
                            }
                        }elseif($highestColumn == 'J'){
                            if (in_array($data['num'], $newArr)) {
                                $dataCover['list'][] = $data['num']; //记录覆盖的数据
                                // $map[$main_field]    = $data[$main_field];
                                // Db::name($table)->where($where)->where($map)->delete();//删除已存在的数据
                                continue;//跳过已存在的考生
                            } else {
                                $dataAdd['list'][] = $data['num']; //记录新增的数据
                            }
                        }
                        $data_list[] = $data;
                    }
                }
            }
            if($highestColumn == 'Q'){
                // 宴会厅
                $banquet = db::name('banquet')->where('hid',$user['hid'])->where('is_del',1)->column('id,name,hid');
                // 宴会厅类型
                $banquet_type = db::name('banquet_types')->where('hid',$user['hid'])->where('is_del',1)->column('id,name,hid');
                // 餐标
                $ds = db::name('ds')->where('hid',$user['hid'])->where('is_del',1)->column('id,name,money,did');
                // 客户经理
                $users = db::name('user')->where('hid',$user['hid'])->column('id,username,hid');
                // 客户来源
                $source = db::name('source')->where('hid',$user['hid'])->where('type',1)->where('is_del',1)->column('id,name,hid');
                foreach ($data_list as $ks => $vs) {
                        if(isset($vs['end'])){
                            unset($data_list[$ks]['end']);
                        }
                        foreach ($banquet as $va) {
                            if(strpos($vs['b_name'],$va['name']) !== false){
                                $data_list[$ks]['bid'] = $va['id'];
                            }
                        }
                        foreach ($banquet_type as $va) {
                            if(strpos($vs['t_name'],$va['name']) !== false){
                                $data_list[$ks]['tid'] = $va['id'];
                            }
                        }
                        foreach ($users as $va) {
                            if(strpos($vs['director'],$va['username']) !== false){
                                $data_list[$ks]['director_id'] = $va['id'];
                            }
                        }
                        foreach ($source as $va) {
                            if(strpos($vs['source'],$va['name']) !== false){
                                $data_list[$ks]['source'] = $va['id'];
                            }
                        }
                        foreach ($ds as $va) {
                            if(strpos($vs['d_name'],$va['name']) !== false){
                                $data_list[$ks]['did'] = $va['id'];
                                $data_list[$ks]['d_money'] = $va['money'];
                                $data_list[$ks]['cid'] = $va['did'];
                            }
                        }
                        if($vs['begin']){
                            $begin = explode("-",$vs['begin']);                   
                            $data_list[$ks]['begin_year'] = $begin[0];
                            $data_list[$ks]['begin_month'] = $begin[1];
                            $data_list[$ks]['begin_day'] = $begin[2];
                            $data_list[$ks]['end_year'] = '';
                            $data_list[$ks]['end_month'] = '';
                            $data_list[$ks]['end_day'] = '';
                            unset($data_list[$ks]['begin']);
                        }
                        if($vs['end']){
                            $begin = explode("-",$vs['end']);                   
                            $data_list[$ks]['end_year'] = $begin[0];
                            $data_list[$ks]['end_month'] = $begin[1];
                            $data_list[$ks]['end_day'] = $begin[2];
                            unset($data_list[$ks]['end']);
                            $data_list[$ks]['is_meeting'] = 1;
                        }else{
                            $data_list[$ks]['is_meeting'] = 2;

                        }
                        if(strpos($vs['sex'],'男') !== false){        
                            $data_list[$ks]['sex'] = '1';
                        }
                    
                        if(strpos($vs['sex'],'女') !== false){        
                            $data_list[$ks]['sex'] = '2';
                        }
                        if($vs['addtime']){
                            $data_list[$ks]['addtime'] = strtotime($vs['addtime']);
                        }

                        if(strpos($vs['begin_night'],'中午') !== false){        
                            $data_list[$ks]['begin_night'] = '1';
                        }
                        if(strpos($vs['begin_night'],'下午') !== false){        
                            $data_list[$ks]['begin_night'] = '2';
                        }
                        if(strpos($vs['begin_night'],'晚上') !== false){        
                            $data_list[$ks]['begin_night'] = '2';
                        }
                        

                        if(strpos($vs['end_night'],'中午') !== false){        
                            $data_list[$ks]['end_night'] = '1';
                        }
                        if(strpos($vs['end_night'],'下午') !== false){        
                            $data_list[$ks]['end_night'] = '2';
                        }
                        if(strpos($vs['end_night'],'晚上') !== false){        
                            $data_list[$ks]['end_night'] = '2';
                        }


                        $data_list[$ks]['hid'] = $user['hid'];
                        $data_list[$ks]['type'] = 2;
                        $data_list[$ks]['paytime'] = time();
                        $data_list[$ks]['modifytime'] = time();

                        $data_list[$ks]['status'] = 1;
                }
                // print_r($data_list);die;
                if($data_list){
                    // print_r($data_list);die;
                    if (Db::name('scheduled')->insertAll($data_list)) {
                        //计算新增、覆盖、跳过的数量
                        $dataAdd['total']   = count($dataAdd['list']);
                        $dataCover['total'] = count($dataCover['list']);
                        $dataSkip['total']  = count($dataSkip['list']);
                        //将新增、覆盖、跳过的数据写入缓存
                        cache('dataAdd', $dataAdd);
                        cache('dataCover', $dataCover);
                        cache('dataSkip', $dataSkip);
                        cache('nextUrl', null);
                        return $this->ajaxReturn(0,'成功导入');
                        // return ["error" => 0, 'message' => '成功导入 '. count($data_list). ' 条数据'];
                    } else {
                        return $this->ajaxReturn(1,'导入失败!请重新导入');
                        // return ["error" => 9, 'message' => '导入失败!请重新导入。'];
                    }
                }else {
                    return $this->ajaxReturn(1,'上传的文件中，没有需要导入的数据!');

                    // return ["error" => 10, 'message' => '上传的文件中，没有需要导入的数据!'];
                }
            }elseif($highestColumn == 'J'){
                // 客户经理
                $users = db::name('user')->where('hid',$user['hid'])->column('id,username,hid');
                // 支付方式
                $pay = db::name('deposit')->where('hid',$user['hid'])->where('type',2)->where('is_del',2)->column('id,name,hid');
                $deposits = db::name('deposit')->where('hid',$user['hid'])->where('type',1)->where('is_del',2)->column('id,name,hid');
                foreach ($data_list as $ks => $vs) {
                   
                    foreach ($pay as $va) {
                        if(strpos($vs['type_name'],$va['name']) !== false){
                            $data_list[$ks]['type_id'] = $va['id'];
                        }
                    }
                    foreach ($deposits as $va) {
                        if(strpos($vs['pay_name'],$va['name']) !== false){
                            $data_list[$ks]['pay_type'] = $va['id'];
                        }
                    }
                    if($vs['addtime']){
                        $data_list[$ks]['addtime'] = strtotime($vs['addtime']);
                    }
                    foreach ($users as $va) {
                        if(strpos($vs['manager'],$va['username']) !== false){
                            $data_list[$ks]['manager_id'] = $va['id'];
                            unset($data_list[$ks]['manager']);

                        }
                    }
                    $data_list[$ks]['status'] = 2;
                    $data_list[$ks]['hid'] = $user['hid'];

                    if(strpos($vs['begin_night'],'中午') !== false){        
                        $data_list[$ks]['begin_night'] = '1';
                    }
                    if(strpos($vs['begin_night'],'下午') !== false){        
                        $data_list[$ks]['begin_night'] = '2';
                    }
                    if(strpos($vs['begin_night'],'晚上') !== false){        
                        $data_list[$ks]['begin_night'] = '2';
                    }
                    

                    if(strpos($vs['end_night'],'中午') !== false){        
                        $data_list[$ks]['end_night'] = '1';
                    }
                    if(strpos($vs['end_night'],'下午') !== false){        
                        $data_list[$ks]['end_night'] = '2';
                    }
                    if(strpos($vs['end_night'],'晚上') !== false){        
                        $data_list[$ks]['end_night'] = '2';
                    }

                    
                    if($vs['order']){
                        $begin = explode("-",$vs['order']);                   
                        $wheres['begin_year'] = $begin[0];
                        $wheres['begin_month'] = $begin[1];
                        $wheres['begin_day'] = $begin[2];
                        
                    if(strpos($vs['begin_night'],'中午') !== false){        
                        $begin_night = '1';
                    }
                    if(strpos($vs['begin_night'],'下午') !== false){        
                        $begin_night = '2';
                    }
                    if(strpos($vs['begin_night'],'晚上') !== false){        
                        $begin_night = '2';
                    }

                        $wheres['begin_night'] = $begin_night;
                        unset($data_list[$ks]['begin_night']);
                        unset($data_list[$ks]['order']);
                    }
                    if($vs['end']){
                        $begin = explode("-",$vs['end']);                   
                        $wheres['end_year'] = $begin[0];
                        $wheres['end_month'] = $begin[1];
                        $wheres['end_day'] = $begin[2];

                        if(strpos($vs['end_night'],'中午') !== false){        
                            $end_night = '1';
                        }
                        if(strpos($vs['end_night'],'下午') !== false){        
                            $end_night = '2';
                        }
                        if(strpos($vs['end_night'],'晚上') !== false){        
                            $end_night = '2';
                        }
    

                        $wheres['end_night'] = $end_night;
                        $wheres['is_meeting'] = 1;
                        unset($data_list[$ks]['end_night']);
                        unset($data_list[$ks]['end']);
                    }
                    $id = db::name('scheduled')->where('hid',$user['hid'])->where($wheres)->value('id');
                    // print_r($id);die;
                    $data_list[$ks]['sid'] = $id;
                }
                if($data_list){
                    // print_r($data_list);die;
                    if (Db::name('scheduled_deposit')->insertAll($data_list)) {
                        //计算新增、覆盖、跳过的数量
                        $dataAdd['total']   = count($dataAdd['list']);
                        $dataCover['total'] = count($dataCover['list']);
                        $dataSkip['total']  = count($dataSkip['list']);
                        //将新增、覆盖、跳过的数据写入缓存
                        cache('dataAdd', $dataAdd);
                        cache('dataCover', $dataCover);
                        cache('dataSkip', $dataSkip);
                        cache('nextUrl', null);
                        return $this->ajaxReturn(0,'成功导入');
                        // return ["error" => 0, 'message' => '成功导入 '. count($data_list). ' 条数据'];
                    } else {
                        return $this->ajaxReturn(1,'导入失败!请重新导入');
                        // return ["error" => 9, 'message' => '导入失败!请重新导入。'];
                    }
                }else {
                    return $this->ajaxReturn(1,'上传的文件中，没有需要导入的数据!');

                    // return ["error" => 10, 'message' => '上传的文件中，没有需要导入的数据!'];
                }
            }
        }
    }
}
    